<?php

namespace plugins\yongtai\controller\Base;


use cmf\controller\PluginAdminBaseController;
use plugins\yongtai\Utils;
use think\facade\Db;
use think\Validate;

class AdminBaseController extends PluginAdminBaseController
{
    public $plugin_name = "yongtai";
    public $image_postfix_url;
    public $error = "";

    protected function initialize()
    {
        parent::initialize();
        $this->image_postfix_url = cmf_get_plugin_config($this->plugin_name)['image_postfix_url'];
        $adminId = cmf_get_current_admin_id();
        if (!empty($adminId)) {
            $this->assign('admin_id', $adminId);
        }
        $this->assign('data', []);
    }

    function Id()
    {
        if (isset($this->request->get()['id'])) {
            return $this->request->get()['id'];
        }
        return $this->GetData()['id'];
    }

    protected function AddPost($model, $check_role = [], $callable_data = false)
    {
        if ($this->request->isPost()) {
            if ($check_role) {
                $this->CheckData($check_role);
            }
            $_data = $callable_data ? $callable_data($this->GetPost()) : $this->GetPost();

            $res = $model->insert($_data);
            $this->AddSucRetSuc($res, $model);
        }
    }

    protected function DelPost($model)
    {
        $id = $this->request->post()['id'];
        $res = $model->DelOne($id);
        $this->DelSucRetSuc($res, $model);
    }

    protected function EditPost($model, $id, $check_role = [], $callable_data = false)
    {
        if ($this->request->isPost()) {
            if ($check_role) {
                $this->CheckData($check_role);
            }
            $data = $callable_data ? $callable_data($this->GetPost()) : $this->GetPost();
            $res = $model->where("id", $id)->save($data);
            $this->EditSucRetSuc($res, $model);
        }
    }

    public function GetError()
    {
        return $this->error;
    }

    protected function GetData()
    {
        $res = $this->request->param();
        if (isset($res['_plugin'])) unset($res['_plugin']);
        if (isset($res['_controller'])) unset($res['_controller']);
        if (isset($res['_action'])) unset($res['_action']);
        return $res;
    }

    protected function GetPost()
    {
        $res = $this->request->post();
        return $res;
    }

    protected function GetPage($page_size = 12, $current_page = 1)
    {
        $data = $this->GetData();
        $page = [];
        $page['page'] = $data['page'] ?? $current_page;
        if (isset($data['limit'])) {
            $page['page_size'] = $data['limit'] ?? $page_size;
        } else {
            $page['page_size'] = $data['page_size'] ?? $page_size;
        }
        $this->assign('page', $page);
        return $page;
    }

    protected function UserId()
    {
        $_data = $this->GetData();
        return $this->CheckToken($_data['token'], $_data['device']);
    }

    protected function CheckToken($token, $device_type)
    {
        $model = Db::name('UserToken');
        $where = [
            'token' => $token,
            'device_type' => $device_type,
        ];
        $info = $model->where($where)->field('user_id')->find();
        if (!$info) $this->error('token错误！');
        return $info['user_id'];
    }

    protected function ReturnSuc($req_condition_data, $model, $suc = '获取成功', $err = false)
    {
        if (!$req_condition_data) {
            if ($err) $str = $err;
            else {
                $str = $model->GetError();
            }
            $this->error($str);
        }
        $this->success($suc);
    }

    protected function AddSucRetSuc($req_condition_data, $model, $suc = '添加成功', $err = "添加失败")
    {
        $this->ReturnSuc($req_condition_data, $model, $suc, $err);
    }

    protected function DelSucRetSuc($req_condition_data, $model, $suc = '删除成功', $err = "删除失败")
    {
        $this->ReturnSuc($req_condition_data, $model, $suc, $err);
    }

    protected function EditSucRetSuc($req_condition_data, $model, $suc = '修改成功', $err = "修改失败")
    {
        $this->ReturnSuc($req_condition_data, $model, $suc, $err);
    }

    protected function CheckData($rule, $message = [], $error = true)
    {
        $data = $this->GetData();
        $_v = new Validate();
        if ($message) $_v->message($message);
        if (!$_v->check($data, $rule)) {
            $this->error = $_v->getError();
            if ($error) $this->error($this->error);
            return false;
        }
        return $data;
    }

    protected function GetEditData($model, $content_key = "content", $_callable = null, $thumbs_name = [])
    {
        $id = $this->Id();
        $data = $model->GetOne($id);
        if (isset($data['thumb'])) {
            $data = Utils::FormatThumb($data, $this->image_postfix_url);
        }
        if ($thumbs_name) {
            foreach ($thumbs_name as $name) {
                $data = Utils::FormatThumb($data, $this->image_postfix_url, $name, "_{$name}");
            }
        }
        if (isset($data[$content_key]) and $data[$content_key])
            $data[$content_key] = htmlspecialchars_decode($data[$content_key]);
        if ($_callable) {
            $data = $_callable($data);
        }
        $data = $data->toArray();
        $this->assign('data', $data);
        return $data;
    }

    protected function GeneratorFilter(array $default_set)
    {
        $data = $this->GetData();
        $filter = $data['filter'] ?? [];
        foreach ($default_set as $key => $value) {
            if (!array_key_exists($key, $filter)) $filter[$key] = $value;
        }
        $this->assign('filter', $filter);
        $this->filter_arr = $filter;
        return $filter;
    }

    /**
     * @param $model
     * @param $filter_key
     * @param string $none_type "null" | "zero" | "isset"
     * @param $callable ($filter_value , $model , $condition)
     * @return mixed
     */
    protected function FilterCallable($model, $filter_key, $none_type, $callable)
    {
        $filter = $this->GetFilter();
        switch ($none_type) {
            case "null":
                $condition = $filter[$filter_key] == null;
                break;
            case "zero":
                $condition = $filter[$filter_key] == 0;
                break;
            default:
                $condition = isset($filter[$filter_key]);
                break;
        }
        if (!$condition) {
            $temp_res = $callable($filter[$filter_key], $model, $condition);
        } else {
            $temp_res = $model;
        }
        return $temp_res;
    }

    protected function GetFilter()
    {
        $filter = [];
        $data = $this->GetData();
        if (isset($data['filter']) and $data['filter']) {
            foreach ($data['filter'] as $key => $__filter) {
                $filter[$key] = $__filter;
            }
        };
        return $filter;
    }

    protected function GenerateFilter($options = [])
    {
        $_options = [
            ['title' => "文本", "width" => "120px", "field" => "title", "type" => "text", "value" => ""],
            ['title' => "选择", "width" => "120px", "field" => "select", "type" => "select", "value" => "",
                "options" => [["value" => 1, "content" => "option1"], ["value" => 2, "content" => "option2"]]
            ],
        ];
        $options = $options ?: array_merge($_options, $options);
//        $filter = $this->GetFilter();
        $_option = [];
        foreach ($options as $option) {
            $__option = $option;
//            if (isset($filter[$option['field']])) {
//            $__option['value'] = $filter[$option['field']];
//            }
            $_option[] = $__option;
        }
        $this->assign('filter_col', $_option);
    }

    protected function Render($class, $func, $file = "admin")
    {
        $class_arr = explode("\\", $class);
        $class_str = Utils::ToUnderScore(substr($class_arr[count($class_arr) - 1], 0, strlen($class_arr[count($class_arr) - 1]) - 10));
        return $this->fetch("{$file}/{$class_str}/" . strtolower($func));
    }

    protected function GenerateForm($form, $class, $func)
    {
        $this->assign('form', $form);
        $form_data = Utils::Map($form, function ($item) {
            return [$item['field'] => $item['value']];
        });
        $_ = [];
        foreach ($form_data as $value) {
            foreach ($value as $key => $_value) {
                $_[$key] = $_value;
            }
        }
        $this->assign('form_data', json_encode($_));
        $class_arr = explode("\\", $class);
        $class_str = $class_arr[count($class_arr) - 1];
        $class_str = substr($class_str, 0, strlen($class_str) - 10);
        $url = cmf_plugin_url("{$this->plugin_name}://{$class_str}/{$func}");
        $this->assign('url', $url);
    }
}
